import requests
from bs4 import BeautifulSoup
import csv


def translate(keyword):
    url = f'https://cn.bing.com/dict/search?q={keyword}&qs=n&form=Z9LH5&sp=-1&pq=perform&sc=8-7&sk=&cvid=7CDE031B23F54AA9941B123E3D4BE4AE&ghsh=0&ghacc=0&ghpl='
    response = requests.get(url)
    text = response.text
    soup = BeautifulSoup(text, 'lxml')
    result = soup.find('div', class_='qdef').find('ul').text
    source = soup.find('div', class_='hd_tf').find('a').attrs['onclick']
    source = source.split(',')[1].replace("'", '')
    down_audio(source, keyword)
    return result
    # print(result)
    # print(source)


def down_audio(url, filename):
    response = requests.get(url)
    with open(f'audios/{filename}.mp3', 'wb') as f:
        f.write(response.content)


def read_text():
    csv_file = open('words.csv', 'w', encoding='utf-8', newline='')
    csv_row = csv.writer(csv_file)
    csv_row.writerow(['english', 'means', 'path'])
    file = open('vocabulary .txt', 'r', encoding='utf-8')
    lines = file.readlines()
    # print(lines)
    for i in lines:
        item = i.replace('\n', '')
        means = translate(item)
        row = [item, means, f'audios/{item}.mp3']
        print(item, means)
        csv_row.writerow(row)


# translate('new')
read_text()
